package com.cxyzy.badgeimageview

import android.content.Context
import android.graphics.Canvas
import android.util.AttributeSet
import android.util.TypedValue
import androidx.appcompat.widget.AppCompatImageView

/**
 * 带角标的ImageView
 */
class BadgeImageView : AppCompatImageView {
    val badge: Badge

    constructor(context: Context?) : super(context) {
        badge = Badge(this, null)
    }

    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
        badge = Badge(this, attrs)
    }

    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        badge = Badge(this, attrs)
    }

    public override fun dispatchDraw(canvas: Canvas) {
        super.dispatchDraw(canvas)
        badge.drawBadge(canvas)
    }

    fun setBadge(number: Long) {
        var text: String?
        text = number.toString()
        if (number > 99) {
            text = "99+"
        } else if (number <= 0) {
            text = null
        }
        setBadge(text)
    }

    fun setBadge(text: String?) {
        badge.badgeText = text
        text?.let {
            val defaultPadding = dp2px(10f).toInt()
            val paddingRight = dp2px(((1 + text.length) * 5).toFloat())
            setPadding(defaultPadding, defaultPadding, paddingRight, 0)
        }
    }

    private fun dp2px(value: Float) = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, resources.displayMetrics).toInt()

}